import { useEffect, useState } from "react";
import { Checkbox, List, Radio } from "antd";
import { getStaff } from "./service";
import styles from "./index.less";
import type { CheckboxChangeEvent } from "antd/es/checkbox";

interface StaffInfo {
  orgName: string;
  userId: number;
  zhName: string;
}

interface Props {
  orgKeys: number[];
  onCheck: (item: StaffInfo[], type?: string) => void;
  className: string;
  deleteKeys: number;
  tabActive: string;
  searchValue: string;
  multiple: boolean;
  initData: StaffInfo[];
}

const Staff: React.FC<Props> = (props) => {
  const [staffList, setStaffList] = useState<StaffInfo[]>([]);
  const [checkKeys, setCheckKeys] = useState<number[]>([]);
  const [total, setTotal] = useState(1);
  const [params, setParams] = useState('');
  const [loading, setLoading] = useState(false);
  const [allChecked, setAllChecked] = useState(false);
  const _getStaff = async (strParams: string, pn: number, zn = '') => {
    setLoading(true);
    try {
      const res = await getStaff({ strParams, pn, zn });
      setStaffList(res.data);
      setTotal(res.countSize);
    } catch (error) {

    } finally {
      setTimeout(async () => {
        setLoading(false);
      }, 1000)
    }
  }

  useEffect(() => {
    if (props.initData.length) {
      setCheckKeys(props.initData.map(item => {
        return item.userId
      }))
    }
  }, [props.initData])

  // 人员多选
  const onCheckMutiple = (item: StaffInfo) => {
    if (checkKeys.includes(item.userId)) {
      setCheckKeys(checkKeys.filter(n => n !== item.userId));
      setAllChecked(false);
    } else {
      const keys = checkKeys.concat(item.userId);
      setCheckKeys(checkKeys.concat(item.userId));
      let isAll = true;
      for (let i = 0; i < staffList.length; i++) {
        if (!keys.includes(staffList[i].userId)) {
          isAll = false;
          break;
        }
      }
      isAll && setAllChecked(true);
    }
    props.onCheck([item]);
  }

  // 人员单选
  const onCheckOne = (item: StaffInfo) => {
    if (checkKeys.includes(item.userId)) {
      setCheckKeys([]);
    } else {
      setCheckKeys([item.userId]);
    }
    props.onCheck([item]);
  }
  const checkAll = (e: CheckboxChangeEvent) => {
    const checked = e.target.checked;
    let list: number[];
    const items: StaffInfo[] = [];
    if (checked) {
      list = [];
      staffList.map(item => {
        if (!checkKeys.includes(item.userId)) {
          list.push(item.userId);
          items.push(item);
        }
      })
      setCheckKeys(checkKeys.concat(list));
      props.onCheck(items, 'add');
    } else {
      list = checkKeys;
      staffList.map(item => {
        const itemIndex = checkKeys.indexOf(item.userId);
        if (itemIndex !== -1) {
          list = list.slice(itemIndex, 1);
        }
      })
      setCheckKeys(list);
      props.onCheck(staffList, 'del');
    }
    setAllChecked(checked);
  }
  useEffect(() => {
    const strParams = props.orgKeys.join(',');
    setParams(params);
    _getStaff(strParams, 0);
  }, [props.orgKeys]);
  useEffect(() => {
    if (props.deleteKeys) {
      setCheckKeys(checkKeys.filter(n => n !== props.deleteKeys));
    }
  }, [props.deleteKeys]);
  useEffect(() => {
    if (props.tabActive === 'staff') {
      // _getAllStaff()
      _getStaff('', 0);
    } else {
      setStaffList([]);
    }
  }, [props.tabActive])
  useEffect(() => {
    _getStaff(params, 0, props.searchValue);
  }, [props.searchValue])
  return (
    <List
      className={props.className}
      header={
        props.multiple && <div className={styles.staffListHead}>
          <span>已选 {checkKeys.length}/{total}</span>
          <Checkbox checked={allChecked} onChange={checkAll} />
        </div>
      }
      itemLayout="horizontal"
      size='small'
      loading={loading}
      split={false}
      pagination={staffList.length ? {
        simple: true,
        pageSize: 10,
        total,
        onChange: page => {
          _getStaff(params, page - 1);
        }
      } : false}
      dataSource={staffList}
      renderItem={item => (
        <div onClick={() => props.multiple ? onCheckMutiple(item) : onCheckOne(item)} key={item.userId} className={styles.itemPanel}>
          <div className={styles.avatar}>{item.zhName[0]}</div>
          <div className={styles.name}>{item.zhName}</div>
          {props.multiple && <Checkbox onClick={() => onCheckMutiple(item)} checked={checkKeys.includes(item.userId)} className={styles.checkBox} />}
          {!props.multiple && <Radio onClick={() => onCheckOne(item)} checked={checkKeys.includes(item.userId)} className={styles.checkBox} />}
        </div>
      )}
    />
  )
}

export default Staff;
